<style lang="less">
@import "../../styles/common.less";
@import "staff.less";
</style>

<template>
  <div class="margin-top-10">
    <Row type="flex" justify="space-between">
      <Row>
        <Button type="primary" @click="handleAddStaff" style="margin-right: 3px">添加学生</Button>
        <Dropdown style="display: none" @on-click="handleAddStaff">
          <Button type="primary">
            添加学生
            <Icon type="arrow-down-b"></Icon>
          </Button>
          <DropdownMenu slot="list">
            <DropdownItem name="staff">正式员工</DropdownItem>
            <DropdownItem name="trainee">实习生</DropdownItem>
          </DropdownMenu>
        </Dropdown>
        <Dropdown @on-click="handleBatchUpload">
          <Button type="primary">
            批量操作
            <Icon type="arrow-down-b"></Icon>
          </Button>
          <DropdownMenu slot="list">
            <DropdownItem name="student">批量上传学员</DropdownItem>
            <!-- <DropdownItem name="feature">批量注册特征</DropdownItem> -->
            <DropdownItem name="avatar">批量注册头像</DropdownItem>
            <DropdownItem name="delStudent">批量删除学员</DropdownItem>
            <DropdownItem name="updateLibrary">批量更新底库</DropdownItem>
            <!-- <DropdownItem name="updateFeature">批量保存特征值</DropdownItem> -->
          </DropdownMenu>
        </Dropdown>
        <!-- <a
          href="#"
          type="primary"
          style="{color:#000;text-decoration:underline;margin-left: 5px;}"
          @click="downloadModal = true"
        >查看批量结果</a> -->
      </Row>
      <Row>
        <Input
          v-model="queryWord"
          @on-enter="searchStudent"
          placeholder="请输入姓名..."
          style="width: 150px;margin-right:3px"
        ></Input>
        <Button @click="searchStudent" type="primary">查询</Button>
      </Row>
    </Row>
    <div class="margin-top-10">
      <Table @on-selection-change="selectionChange" :columns="studentColumn" :data="studentData" :loading="tableLoading"></Table>
    </div>
    <Row type="flex" justify="end" class="margin-top-10">
      <Page
        :total="totalStudent"
        :current="currentPage"
        :page-size="pageSize"
        @on-change="getStudent"
        show-total
      >显示第{{currentIndex + 1}}-{{currentIndex + pageSize}}条，总数为{{totalStudent}}条</Page>
    </Row>

    <Modal
      v-model="addStudentModal"
      v-bind:title="modalTitle"
      :scrollable="true"
      class-name="vertical-center-modal"
      :mask-closable="false"
      @on-cancel="resetForm('studentInfoForm')"
    >
      <Form
        ref="studentInfoForm"
        :label-width="55"
        :model="studentInfo"
        :rules="studentInfoRules"
      >
        <!--照片-->
        <!-- <Row type="flex" justify="center" style="margin-bottom: 5px">
          <div style="margin-bottom: 10px">
            <a href="javascript:void(0)" class="staff-file" ref="avatar_staff">
              <input
                type="file"
                ref="avatar_input"
                accept="image/png, image/jpeg, image/jpg"
                @change="preview_staff"
                title=""
              >
            </a>
          </div>
        </Row> -->
        <Row type="flex" justify="space-between">
          <Col style="width: 48.5%">
            <FormItem label="姓名" prop="user_name">
              <Input v-model.trim="studentInfo.user_name" placeholder="请填写姓名"/>
            </FormItem>
            <FormItem label="性别" prop="user_sex">
              <RadioGroup v-model="studentInfo.user_sex">
                <Radio label="1">男</Radio>
                <Radio label="0">女</Radio>
              </RadioGroup>
            </FormItem>
            <FormItem label="学校" prop="user_school">
              <Input
                placeholder="请填写学校"
                style="width: 100%"
                v-model.trim="studentInfo.user_school"
              />
            </FormItem>
            <FormItem label="邮箱" prop="user_email">
              <Input placeholder="请填写邮箱" v-model.trim="studentInfo.user_email"/>
            </FormItem>
          </Col>
          <Col style="width: 48.5%">
            <FormItem label="学号" prop="user_num">
              <Input
                placeholder="请填写学号"
                style="width: 100%"
                :maxlength="20"
                v-model.trim="studentInfo.user_num"
              />
            </FormItem>
            <FormItem label="电话" prop="user_phone">
              <Input placeholder="电话（可选）" v-model.trim="studentInfo.user_phone"/>
            </FormItem>
            <FormItem label="班级" prop="user_class">
              <Input
                placeholder="请填写班级"
                style="width: 100%"
                v-model.trim="studentInfo.user_class"
              />
            </FormItem>
          </Col>
        </Row>
      </Form>
      <div slot="footer">
        <Button type="primary" @click="handleSubmitStaff('studentInfoForm')">提交</Button>
      </div>
    </Modal>

    <Modal
      width="532"
      style="{margin-top:10px}"
      :closable="false"
      :mask-closable="false"
      v-model="modAvatar" 
      >
      <spin v-show="featureLoading" size="large" fix></spin>
      <a class="ivu-modal-close" @click="modAvatar = false">
        <Icon type="ios-close-empty"></Icon>
      </a>
      <div slot="header" class="ivu-modal-header-inner">修改【{{modAvatarInfo.user_name}}】的人脸特征</div>
      <Row v-if="modUpload">
        <uploader
          :count="uploadedAvatarRegsLength"
          :maxlength="FEATURE_MAX"
          @fileChange="handleUserAvatarRegUpload"
          @fileAdd="handleUserAvatarRegAdd"
        >
          <!-- Uploader的标题slot -->
          <span slot="title">上传特征</span>
          <!-- 需要预览时，增加UploaderFiles容器 -->
          <uploaderfiles slot="uploader-files">
            <uploaderfile
              v-for="(imgSrc,i) in uploadedAvatarRegs"
              :key="i"
              :image-url="createSnapshot(imgSrc)"
              @click="handleUserAvatarRegRemove(imgSrc)"
            ></uploaderfile>
          </uploaderfiles>
        </uploader>
      </Row>
      <Row type="flex" justify="start" v-else>
        <img
          v-for="(imgSrc,i) in modAvatarInfo.avatarReg"
          :key="i"
          style="width:80px;height:80px;margin:10px;object-fit: cover;cursor: pointer;"
          :src="imgSrc"
          @click="handleShowUserAvatarReg(i,modAvatarInfo.avatarReg.length,imgSrc)"
        >
      </Row>
      <div slot="footer" v-if="modUpload">
        <Button type="primary" size="large" @click="uploadUserAvatarReg(modAvatarInfo.user_id)">确认上传</Button>
      </div>
      <div slot="footer" v-else>
        <Button
          type="error"
          size="large"
          @click="handleDelAllFeature(modAvatarInfo.user_id, modAvatarInfo.user_name)"
        >全部删除</Button>
        <Button type="primary" size="large" @click="modUpload=true">重新上传</Button>
      </div>
    </Modal>
    <Modal v-model="uploadModal" @on-cancel="hideUploadModal">
      <div slot="header">
        <p>
          导入表格
          <span style="font-weight: 100;font-size: 12px;margin-left: 5px">
            (请严格按照
            <a :href="excelFile" download="模板.xlsx">模板</a>格式上传表格)
          </span>
        </p>
      </div>
      <HorizonUploader ref="uploader"></HorizonUploader>
      <div slot="footer">
        <Button type="primary" @click="handleUpload">上传</Button>
      </div>
    </Modal>
    <Modal
      v-model="featureModal"
      class="staff-imgShow"
      :closable="false"
      style="{margin-top: 10px}"
      >
      <a class="ivu-modal-close" @click="featureModal = false">
        <Icon type="ios-close-empty"></Icon>
      </a>
      <div slot="header" class="ivu-modal-header-inner">{{featureModalTitle}}</div>
      <div class="ivu-carousel">
        <Button
          class="left ivu-carousel-arrow ivu-carousel-arrow-hover"
          @click="handleImgLeft"
          v-show="previewImgLeftVisible"
        >
          <Icon type="chevron-left"></Icon>
        </Button>
        <Row type="flex" justify="center">
          <div
            :style="{backgroundImage:imgSrc}"
            style="height: 100%;width: 100%;background-size: auto 100%;background-repeat: no-repeat;background-position: center top;"
          >
            <div style="padding: 60%"></div>
          </div>
        </Row>
        <Button
          class="right ivu-carousel-arrow ivu-carousel-arrow-hover"
          @click="handleImgRight"
          v-show="previewImgRightVisible"
        >
          <Icon type="chevron-right"></Icon>
        </Button>
      </div>
    </Modal>
    <DownloadTableModal v-model="downloadModal"></DownloadTableModal>
    <UploadFeatureModal
      v-model="uploadFeatureModal"
      user_type="register"
      title="员工特征上传"
      file_type="feature"
    ></UploadFeatureModal>
    <UploadAvatarModal
      v-model="uploadAvatarModal"
      user_type="register"
      title="学员头像上传"
      file_type="avatar"
    ></UploadAvatarModal>
  </div>
</template>

<script>
import {
  getStudentData,
  getAvatar,
  addStudent,
  updateStudent,
  batchUpdateStudent,
  batchSaveFeature,
  deleteStudent,
  saveStudentFeature,
  deleteStudentFeature,
  regFeature,
  getFeature,
  delFeature,
  uploadStudentData,
  registBatch,
  recovery
} from "../../controllers/student";

import Uploader from "../../views/weiget/uploader.vue";
import Uploaderfile from "../../views/weiget/uploader-file.vue";
import Uploaderfiles from "../../views/weiget/uploader-files.vue";
import ImageUtils from "@/libs/image.js";
import HorizonUploader from "./components/HorizonUploader.vue";
import DownloadTableModal from "./DownloadTableModal.vue";
import UploadFeatureModal from "./UploadFeatureModal.vue";
import UploadAvatarModal from "./UploadAvatarModal.vue";


import Tooltip from "../../../node_modules/iview/src/components/tooltip/tooltip";
import Btn from "../../../node_modules/iview/src/components/button/button";
import Constant from "../../libs/constants";
import _ from "lodash";
import pic from "../../images/upload.png";
import fakeAvatar from "../../images/default_avatar.png";
import DateUtils from "../../../node_modules/iview/src/utils/date";
import iconDelete from "../../images/delete.png";
import iconEdit from "../../images/edit.png";
import iconFeature from "../../images/feature.png";

import excelFile from "../../assets/studentExcel.xlsx";

export default {
  components: {
    Uploader,
    Uploaderfile,
    Uploaderfiles,
    HorizonUploader,
    DownloadTableModal,
    UploadFeatureModal,
    UploadAvatarModal,
    Tooltip,
    Btn
  },
  data() {
    return {
      FEATURE_MIN: Constant.FEATURE_MIN,
      FEATURE_MAX: Constant.FEATURE_MAX,
      IMG_WIDTH_MIN: Constant.IMG_WIDTH_MIN,
      IMG_WIDTH_MAX: Constant.IMG_WIDTH_MAX,
      IMG_HEIGHT_MIN: Constant.IMG_HEIGHT_MIN,
      IMG_HEIGHT_MAX: Constant.IMG_HEIGHT_MAX,
      addStudentModal: false,
      modAvatar: false,
      modUpload: false,
      modAvatarInfo: {
        user_id: "",
        user_name: "",
        avatarReg: []
      },
      previewImgInfo: {
        currentIndex: 0,
        total: 0
      },
      uploadedAvatarRegs: [],
      tableLoading: true,
      queryWord: "",
      pageSize: Constant.PAGE_SIZE,
      currentPage: 1,
      totalStudent: 0,
      studentColumn: [
        {
          type: 'selection',
          width: 60,
          align: 'center',
          fixed:'left'
        },
        {
          title: "学号",
          align: "center",
          key: "user_num",
          width: 200
        },
        {
          title: "姓名",
          key: "user_name",
          align: "center",
          width: 200
        },
        {
          title: "学校",
          key: "user_school",
          ellipsis: true,
          align: "center",
          width: 200
        },
        {
          title: "操作",
          align: "center",
          minWidth: 400,
          render: (h, { row, column, index }) => {
            const _id = row._id;
            const user_name = row.user_name;
            return (
              <div class="operate-column">
                {/* 
                <Tooltip content="特征修改" placement="bottom">
                  <Btn
                    style={{ background: `url( ${iconFeature})` }}
                    onClick={() => this.handleEditFeature(user_id, user_name)}
                  />
                </Tooltip>
                */}
                  <Btn
                    type="text"
                    onClick={() => this.handleEditStudent(row)}
                  >编辑</Btn>
                  <Btn
                    type="text"
                    onClick={() => this.handleDelStudent(_id, user_name)}
                  >删除</Btn>
                  {/* 
                    <Btn
                    type="text"
                      onClick={() => this.handleSaveFeatureStudent(_id, user_name)}
                    >保存/更新特征值</Btn>
                    <Btn
                      type="text"
                      disabled={!row.feature_id}
                      onClick={() => this.handleDelFeatureStudent(_id, user_name)}
                    >删除特征值</Btn>
                  */}
              </div>
            );
          }
        }
      ],
      studentData: [],
      selectionRows:[],
      edit_flag: false,
      user_id: "",
      studentInfo: {
        _id:'',
        user_name: "",
        user_sex: "",
        user_avatar: "",
        user_num: "",
        user_school: "",
        user_class: "",
        user_phone: "",
        user_email: "",
      },
      modalTitle: "添加正式员工",
      studentInfoRules: {
          // user_id: [
          //   { required: true, message: "账号不可以为空", trigger: "blur" }
          // ],
          user_name: [
            { required: true, message: "姓名不可以为空", trigger: "blur" }
          ],
          user_num: [
              {required: true, message: "学号不可以为空", trigger: "blur"},
              {
                pattern: /^[\da-zA-Z]+$/,
                message: "学号格式不正确",
                trigger: "blur"
              }
          ],
          user_sex: [
              {required: true, message: "请选择性别", trigger: "blur"}
          ],
          user_school: [],
          user_class: [],
          user_email: [
            { type: "email", message: "邮箱格式不正确", trigger: "blur" }
          ],
          user_phone: [
            {
              pattern: /^1\d{10}$/,
              message: "电话格式不正确",
              trigger: "blur"
            }
          ]
      },
      departmentList: [],
      uploadModal: false,
      excelFile: excelFile,
      featureModal: false,
      imgSrc: "",
      featureLoading: true,
      downloadModal: false,
      uploadFeatureModal: false,
      uploadAvatarModal: false
    };
  },
  computed: {
    currentIndex: function() {
      return (this.currentPage - 1) * this.pageSize;
    },
    uploadedAvatarRegsLength: function() {
      return this.uploadedAvatarRegs.length;
    },
    featureModalTitle: function() {
      let i = this.previewImgInfo.currentIndex + 1;
      let cnt = this.previewImgInfo.total;
      return i + "/" + cnt;
    },
    previewImgLeftVisible: function() {
      return this.previewImgInfo.currentIndex > 0;
    },
    previewImgRightVisible: function() {
      return this.previewImgInfo.currentIndex < this.previewImgInfo.total - 1;
    }
  },
  //待考虑：初次加载表格的时机
  created() {
    this.loadStudentData();
  },
  mounted() {
    document.addEventListener("keydown", this.handleKeyDown);
  },
  beforeDestroy() {
    document.removeEventListener("keydown", this.handleKeyDown);
  },
  watch:{
    uploadAvatarModal(val){
      if(!val){
        this.searchStudent()
      }
    }
  },
  methods: {
    getStudent(page) {
      //获取分页参数，请求后端数据
      //console.log(page);
      //检验页码上下限
      this.currentPage = page;
      this.tableLoading = true;
      this.loadStudentData();
    },
    selectionChange(selection){
      this.selectionRows = selection
    },
    handleAddStaff(type) {
      this.edit_flag = false;
      this.user_id = "";
      this.modalTitle = "添加学生";
      this.studentInfo._id = null;
      this.addStudentModal = true;
    },
    handleBatchUpload(type) {
      switch (type) {
        case "student":
          this.uploadModal = true;
          break;
        case "feature":
          this.uploadFeatureModal = true;
          break;
        case "avatar":
          this.uploadAvatarModal = true;
          break;
        case "delStudent":
          if(this.selectionRows.length<=0){
            return this.$Message.error('请选择学员')
          }
          const ids = this.selectionRows.map(item=>item._id)
          this.$Modal.confirm({
            title: "确认",
            content: "删除选中的学员吗？",
            onOk: () => {
              // 删除基本信息
              deleteStudent({ _id: ids }).then(res => {
                if (res.code === 0) {
                  this.$Message.success("删除成功!");
                  this.getStudent(1);
                }
              });
            }
          });
          break;
        case "updateLibrary":
          if(this.selectionRows.length<=0){
            return this.$Message.error('请选择学员')
          }
          const _ids = this.selectionRows.map(item=>item._id)
          this.$Modal.confirm({
            title: "确认",
            content: "更新选中的学员到设备底库吗？",
            onOk: () => {
              batchUpdateStudent({ ids:_ids }).then(res => {
                if (res.code === 0) {
                  this.$Message.success(res.msg||"操作成功!");
                  this.getStudent(1);
                }
              });
            }
          });
          break;
        case "updateFeature":
          if(this.selectionRows.length<=0){
            return this.$Message.error('请选择学员')
          }
          const _ids_ = this.selectionRows.map(item=>item._id)
          this.$Modal.confirm({
            title: "确认",
            content: "保存选中学员的特征值吗？",
            onOk: () => {
              batchSaveFeature({ ids:_ids_ }).then(res => {
                if (res.code === 0) {
                  this.$Message.success(res.msg||"操作成功!");
                  this.getStudent(1);
                }
              });
            }
          });
          break;
      }
    },
    handleSubmitStaff(form) {
      this.$refs[form].validate(valid => {
        if (valid) {
          if(this.edit_flag){
            updateStudent(
            this.studentInfo
          ).then(res => {
            if (res.code == 0) {
              this.$Message.success(res.msg||"提交成功!");
              this.addStudentModal = false;
              this.resetForm(form);
              this.getStudent(this.currentPage);
            }else if(res.code === 3){
                this.addStudentModal = false;
                this.resetForm(form);
                this.getStudent(this.currentPage);
              }
          });
          }else{
            addStudent(
              this.studentInfo
            ).then(res => {
              if (res.code == 0) {
                this.$Message.success(res.msg||"提交成功!");
                this.addStudentModal = false;
                this.resetForm(form);
                this.getStudent(this.currentPage);
              }else if(res.code === 3){
                this.addStudentModal = false;
                this.resetForm(form);
                this.getStudent(this.currentPage);
              }
            });
          }
        } else {
          this.$Message.error("填写项目验证失败!");
        }
      });
    },
    handleDelStudent(id, name) {
      this.$Modal.confirm({
        title: "确认",
        content: "删除学员【" + name + "】？",
        onOk: () => {
          // 删除基本信息
          deleteStudent({ _id: [id] }).then(res => {
            if (res.code === 0) {
              this.$Message.success("删除成功!");
              this.getStudent(this.currentPage);
            }
          });
        }
      });
    },
    handleSaveFeatureStudent(id, name){
      this.$Modal.confirm({
        title: "确认",
        content: "保存或更新【" + name + "】的特征值？",
        onOk: () => {
          // 保存特征值
          saveStudentFeature({ id }).then(res => {
            if (res.code === 0) {
              this.$Message.success("保存成功!");
              this.getStudent(this.currentPage);
            }
          });
        }
      });
    },
    handleDelFeatureStudent(id, name){
      this.$Modal.confirm({
        title: "确认",
        content: "删除【" + name + "】的特征值？",
        onOk: () => {
          // 删除特征值
          deleteStudentFeature({ id }).then(res => {
            if (res.code === 0) {
              this.$Message.success("删除成功!");
              this.getStudent(this.currentPage);
            }
          });
        }
      });
    },
    handleEditStudent(row) {
      this.edit_flag = true;
      const data = row || {};

      this.modalTitle = "编辑学生信息";
      let type = "staff";
      let avatar = "avatar_staff";
      this.studentInfo._id = data._id;
      this.studentInfo.user_name = data.user_name;
      this.studentInfo.user_num = data.user_num;
      // this.studentInfo.user_avatar = data.user_avatar;
      this.studentInfo.user_avatar = '';
      this.studentInfo.user_school = data.user_school;
      this.studentInfo.user_class = data.user_class;
      this.studentInfo.user_email = data.user_email;
      this.studentInfo.user_sex = data.user_sex+'';
      this.studentInfo.user_phone = data.user_phone;
      //头像
      let img = this.studentInfo.user_avatar
        ? 'data:image/jpeg;base64,'+this.studentInfo.user_avatar
        : pic;
      this.$refs[avatar].style.backgroundImage = "url(" + img + ")";
      this.addStudentModal = true;
    },
    searchStudent() {
      //to-do:检验关键词
      this.currentPage = 1;
      this.tableLoading = true;
      this.loadStudentData();
    },
    loadStudentData() {
      this.selectionRows = [];
      getStudentData(this.currentPage, this.pageSize, this.queryWord)
        .then(json => {
          let { total, data } = transStudentData(json);
          this.totalStudent = total;
          this.studentData = data;
          this.tableLoading = false;
          let tmp = _.map(data, item => item.uid);
          return tmp;
        })
        // .then(uids => this.asyncAvatar(uids));
    },
    asyncAvatar(uids) {
      _.forEach(uids, (uid, index) => {
        getAvatar(uid).then(json => {
          if (this.studentData[index] === undefined) {
            console.log(
              "存在数据加载错误，可能在异步过程完成前修改了原始的表数据"
            );
          }
          let result = transAvatar(json);
          // this.studentData[index].avatarDis = result.user_avatar;
          this.studentData[index].avatarReg = result.user_feature;
        });
        return true;
      });
    },
    handleDelAllFeature(userId, userName) {
      this.$Modal.confirm({
        title: "确认",
        content: "删除【" + userName + "】的特征库？",
        onOk: () => {
          delFeature({ user_id: userId }).then(res => {
            if (res.code === 0) {
              this.$Message.success("删除成功!");
              this.modAvatar = false;
              this.getStudent(this.currentPage);
            } else {
              this.$Message.error("删除失败!");
            }
          });
        }
      });
    },
    handleEditFeature(user_id, user_name) {
      this.uploadedAvatarRegs.splice(0, this.uploadedAvatarRegs.length);
      // 通过id检索全部人脸特征
      this.modAvatarInfo.user_id = user_id;
      this.modAvatarInfo.user_name = user_name;
      this.modAvatarInfo.avatarReg = [];
      this.featureLoading = true;
      this.modUpload = false;
      this.modAvatar = true;
      getFeature(user_id).then(res => {
        if (res.data && res.data.length > 0) {
          this.modAvatarInfo.avatarReg = _.map(
            res.data,
            i => "data:image/jpg;base64," + i
          );
          this.modUpload = false;
        } else {
          this.modUpload = true;
        }
        this.featureLoading = false;
      });
    },
    handleUserAvatarRegUpload(imgs) {
      _.forEach(imgs, file => {
        if (["image/jpg", "image/jpeg", "image/png"].indexOf(file.type) < 0) {
          return false;
        }
        if (this.uploadedAvatarRegsLength >= this.FEATURE_MAX) {
          return false;
        }

        // base64
        const reader = new FileReader();
        let _this = this;
        let name = file.name;
        reader.onload = function(e) {
          let img = new Image();
          img.onload = function() {
            let width = img.width;
            let height = img.height;
            if (width < _this.IMG_WIDTH_MIN || width > _this.IMG_WIDTH_MAX) {
              let errMsg =
                "图片" +
                name +
                "宽度存在问题，应在(" +
                _this.IMG_WIDTH_MIN +
                "-" +
                _this.IMG_WIDTH_MAX +
                ")之间";
              _this.$Message.error(errMsg);
            } else if (
              height < _this.IMG_HEIGHT_MIN ||
              height > _this.IMG_HEIGHT_MAX
            ) {
              let errMsg =
                "图片" +
                name +
                "高度存在问题，应在(" +
                _this.IMG_HEIGHT_MIN +
                "-" +
                _this.IMG_HEIGHT_MAX +
                ")之间";
              _this.$Message.error(errMsg);
            } else {
              _this.uploadedAvatarRegs.push({
                picdata: e.target.result.split(",")[1],
                type: file.type.split("/")[1]
              });
            }
          };
          img.src = e.target.result;
        };
        reader.readAsDataURL(file);
        return true;
      });
    },
    handleUserAvatarRegAdd(img, width, height) {
      if (["image/jpg", "image/jpeg", "image/png"].indexOf(img.type) < 0) {
        return false;
      }
      if (this.uploadedAvatarRegsLength >= this.FEATURE_MAX) {
        return false;
      }
      let name = img.name;
      if (width < this.IMG_WIDTH_MIN || width > this.IMG_WIDTH_MAX) {
        let errMsg =
          "图片" +
          name +
          "宽度存在问题，应在(" +
          this.IMG_WIDTH_MIN +
          "-" +
          this.IMG_WIDTH_MAX +
          ")之间";
        this.$Message.error(errMsg);
        return;
      } else if (height < this.IMG_HEIGHT_MIN || height > this.IMG_HEIGHT_MAX) {
        let errMsg =
          "图片" +
          name +
          "高度存在问题，应在(" +
          this.IMG_HEIGHT_MIN +
          "-" +
          this.IMG_HEIGHT_MAX +
          ")之间";
        this.$Message.error(errMsg);
        return;
      }
      const reader = new FileReader();
      let _this = this;
      reader.onload = function(e) {
        _this.uploadedAvatarRegs.push({
          picdata: e.target.result.split(",")[1],
          type: img.type.split("/")[1]
        });
      };
      reader.readAsDataURL(img);
    },
    handleUserAvatarRegRemove(item) {
      // 从 upload 实例删除数据
      this.uploadedAvatarRegs.splice(this.uploadedAvatarRegs.indexOf(item), 1);
    },
    createSnapshot(item) {
      return "data:image/" + item.type + ";base64," + item.picdata;
    },
    uploadUserAvatarReg(userId) {
      //检查待上传文件
      //组装上传信息
      //发起请求
      //处理上传过程
      //成功上传or错误
      //清除URL.revokeObjectURL(objectURL);//注销内存使用。

      // TODO
      if (this.uploadedAvatarRegsLength < this.FEATURE_MIN) {
        this.$Message.info("请选择特征图");
        return;
      }

      // 注册特征
      regFeature({
        user_id: userId,
        feature_pic: this.uploadedAvatarRegs
      }).then(res => {
        if (res.code === 0) {
          this.$Message.success("注册成功");
          this.modAvatar = false;
          this.getStudent(this.currentPage);
        }
      });
    },
    preview_staff(e) {
      this.preview(e, "avatar_staff", "staff");
    },
    preview(e, id, type) {
      let file = e.target.files[0];
      ImageUtils.compress(
        file,
        {
          compress: {
            width: 480,
            height: 480,
            quality: 0.8
          },
          type: "file"
        },
        (res, w, h) => {
          if (res) {
            let reader = new FileReader();
            reader.onload = () => {
              this.$refs[id].style.backgroundImage =
                "url('" + reader.result + "')";
              // this.studentInfo.user_avatar = reader.result;
              this.studentInfo.user_avatar = reader.result.split(",")[1];
              reader.onload = null;
            };
            reader.readAsDataURL(res);

            // // 更新头像
            // if (this.edit_flag) {
            //     let data = new FormData();
            //     data.append('avatar', res);
            //     data.append('user_id', this.user_id);
            //     updateAvatar(data).then(res => {
            //         this.$Message.success("头像更新成功!");
            //     })
            // }
          } else {
            this.$Message.error("图片过大，请更换");
          }
        }
      );
    },
    resetForm(form) {
      this.edit_flag = false;
      //解决对话框消失的时候字体变化问题
      setTimeout(() => {
        this.$refs[form].resetFields();
        this.$refs['avatar_input'].value = null;
        this.$refs['avatar_staff'].style.backgroundImage = "url(" + pic + ")";
        this.studentInfo.user_avatar = "";
      }, 500);
    },
    handleUpload() {
      if (!this.$refs["uploader"].hasFile) {
        this.$Message.error("请先选择文件");
        return;
      }
      var formData = new FormData();
      formData.append("student_xlsx", this.$refs["uploader"].file);
      uploadStudentData(formData).then(json => {
        if (json.code == 0) {
          this.$Message.success(json.msg);
          this.hideUploadModal();
          this.getStudent(this.currentPage);
        }
      });
    },
    hideUploadModal() {
      this.$refs["uploader"].reset();
      this.uploadModal = false;
    },
    handleShowUserAvatarReg(i, cnt, img) {
      this.imgSrc = "url(" + img + ")";
      this.previewImgInfo.currentIndex = i;
      this.previewImgInfo.total = cnt;
      this.featureModal = true;
    },
    handleKeyDown(e) {
      switch (e.keyCode) {
        case 27:
          if (this.featureModal) {
            this.featureModal = false;
          } else if (this.modAvatar) {
            this.modAvatar = false;
          }
          break;
        case 37:
          this.handleImgLeft();
          break;
        case 39:
          this.handleImgRight();
          break;
      }
    },
    handleImgLeft() {
      let index = this.previewImgInfo.currentIndex;
      if (index > 0) {
        this.previewImgInfo.currentIndex--;
        this.imgSrc = "url(" + this.modAvatarInfo.avatarReg[index - 1] + ")";
      }
    },
    handleImgRight() {
      let index = this.previewImgInfo.currentIndex;
      if (index < this.modAvatarInfo.avatarReg.length - 1) {
        this.previewImgInfo.currentIndex++;
        this.imgSrc = "url(" + this.modAvatarInfo.avatarReg[index + 1] + ")";
      }
    }
  }
};

function transStudentData(json) {
  //检测状态码
  if (json.code !== 0) {
    //非正常就返回空表
    return { total: 0, result: {} };
  }
  let data = json.data;
  //检测数据块存在及长度
  if (data === undefined) {
    return { total: 0, result: {} };
  }

  let { total, result } = data;

  //to-do:检查data成员

  // let temp = _.map(result, v => ({
  //   user_type: v["user_type"],
  //   uid: v["user_id"],
  //   name: v["user_name"],
  //   employee: v["user_type"] > 0 ? true : false,
  //   department: v["user_dept"],
  //   user_dept_disp: v["user_dept_disp"],
  //   employedTime: v["c_at"] || "无数据",
  //   avatarDis: v["user_avatar"], //to-do:缺占位图base64
  //   avatarReg: [],
  //   user_no: v["user_no"],
  //   user_phone: v["user_phone"],
  //   user_email: v["user_email"],
  //   user_position: v["user_position"],
  //   access_from: v["access_from"],
  //   access_to: v["access_to"],
  //   user_sex: v["user_sex"] === 0 ? "0" : "1",
  //   user_mark: v["user_mark"],
  //   user_mark2: v["user_mark2"]
  // }));
  return {
    total,
    data: result
  };
}

function transAvatar(json) {
  //检测状态码
  if (json.code !== 0) {
    //非正常就返回空表
    return { user_avatar: "", user_feature: ["", "", ""] };
  }
  let data = json.data;
  //检测数据块存在及长度
  if (data === undefined || data.length === 0) {
    return { user_avatar: "", user_feature: ["", "", ""] };
  }
  //提取->检验->组装
  return data[0];
}
</script>